package com.vision.util.http.down.thread;

import com.google.common.collect.Lists;
import com.vision.util.http.down.AbsDownEntity;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 项目名称：vision
 * 类名称： DownVideoExecutorPool
 * 类描述：
 * 创建人：zc
 * 创建时间：2017-01-06 16:51
 * 修改人：
 * 修改时间：
 * 修改备注：
 *
 * @version 1.0
 */
public class DownVideoExecutorPool<T extends AbsDownEntity> {

    // 下载视频线程  使用线程池
    private ThreadPoolExecutor executorService;

    private List<Future<T>> futureList = Lists.newArrayList();

    public DownVideoExecutorPool(int nThreads) {
        executorService = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
    }

    public DownVideoExecutorPool(int nThreads, String name) {
        executorService = new ThreadPoolExecutor(nThreads, nThreads,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), getThreadFactory(name));
    }


    public void putDownVideoTask(Callable<T> callable, boolean needResult) {
        Future<T> submit = executorService.submit(callable);
        if (needResult) {
            futureList.add(submit);
        }
    }

    public int getThreadCount() {
        return ((ThreadPoolExecutor) executorService).getActiveCount();
    }

    public int getNThread() {
        return executorService.getCorePoolSize();
    }

    private ThreadFactory getThreadFactory(String name) {
        return new MyThreadFactory(name);
    }

    public List<Future<T>> getFutureList() {
        return futureList;
    }

}
